package hos.util.carash;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.text.format.Formatter;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;

import hos.core.ActivityManager;
import hos.java.util.CrashUtils;

/**
 * <p>Title: CrashHandler </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @version : 1.0
 * @date : 2022/3/30 23:37
 */
public class CrashAndroid {

    private final static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.CHINA);

    private final static String LAUNCH_TIME = formatter.format(new Date());

    public static void init(final Context context, final File crashDir, final CrashUtils.OnCrashListener onCrashListener) {
        CrashUtils.init(crashDir, new CrashUtils.OnCrashListener() {
            @Override
            public void onCrash(String crashFile, String time, String info) {
                if (onCrashListener != null) {
                    onCrashListener.onCrash(crashFile, time, collectDeviceInfo(context, time, info));
                }
            }
        });
    }

    public static void init(final Context context, final String crashDirPath, final CrashUtils.OnCrashListener onCrashListener) {
        CrashUtils.init(crashDirPath, new CrashUtils.OnCrashListener() {
            @Override
            public void onCrash(String crashFile, String time, String info) {
                if (onCrashListener != null) {
                    onCrashListener.onCrash(crashFile, time, collectDeviceInfo(context, time, info));
                }
            }
        });
    }

    /**
     * 设备类型、OS本版、线程名、前后台、使用时长、App版本、升级渠道
     * CPU架构、内存信息、存储信息、permission权限
     */
    private static String collectDeviceInfo(Context context, String time, String info) {
        StringBuilder sb = new StringBuilder();
        sb.append("brand=").append(Build.BRAND).append("\n");// huawei,xiaomi
        sb.append("rom=").append(Build.MODEL).append("\n"); //sm-G9550
        sb.append("os=").append(Build.VERSION.RELEASE).append("\n");//9.0
        sb.append("sdk=").append(Build.VERSION.SDK_INT).append("\n");//28
        sb.append("launch_time=").append(LAUNCH_TIME).append("\n");//启动APP的时间
        sb.append("crash_time=").append(time).append("\n");//crash发生的时间
        sb.append("forground=").append(!ActivityManager.getInstance().isBackground()).append("\n");//应用处于前后台
        sb.append("thread=").append(Thread.currentThread().getName()).append("\n");//异常线程名
        sb.append("cpu_arch=").append(Build.CPU_ABI).append("\n");//armv7 armv8

        //app 信息
        PackageInfo packageInfo = null;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            sb.append("version_code=").append(packageInfo.versionCode).append("\n");
            sb.append("version_name=").append(packageInfo.versionName).append("\n");
            sb.append("package_name=").append(packageInfo.packageName).append("\n");
            sb.append("requested_permission=").append(Arrays.toString(packageInfo.requestedPermissions)).append("\n");//已申请到那些权限
        } catch (PackageManager.NameNotFoundException nameNotFoundException) {
            nameNotFoundException.printStackTrace();
        }
        try {
            //统计一波 存储空间的信息，
            android.app.ActivityManager.MemoryInfo memInfo = new android.app.ActivityManager.MemoryInfo();
            android.app.ActivityManager ams =
                    (android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            ams.getMemoryInfo(memInfo);
            sb.append("availMem=").append(Formatter.formatFileSize(context, memInfo.availMem)).append("\n");//可用内存
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                sb.append("totalMem=").append(Formatter.formatFileSize(context, memInfo.totalMem)).append("\n");//设备总内存
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }

        try {
            File file = Environment.getExternalStorageDirectory();
            StatFs statFs = new StatFs(file.getPath());
            long availableSize;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                availableSize = statFs.getAvailableBlocksLong() * statFs.getBlockSizeLong();
            } else {
                availableSize = (long) statFs.getAvailableBlocks() * statFs.getBlockSize();
            }
            sb.append("availStorage=").append(Formatter.formatFileSize(context, availableSize)).append("\n");//存储空间
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        sb.append(info);
        return sb.toString();
    }
}
